//
//  An_CompetitionOrderVc.m
//  Zhiche-Carriage
//
//  Created by Code_浅蓝 on 17/5/24.
//  Copyright © 2017年 Code_An. All rights reserved.
//

#import "An_CompetitionOrderVc.h"

#import "DriverOrderCell.h"
#import "An_ComptitionOrdersModel.h"
#import "CompitionOrdersDetailVc.h"

#import "TopBackView.h"
#import "RootViewController.h"
#import "OrderdetailVC.h"//订单详情

#import "NSDictionary+jmCategory.h"

@interface An_CompetitionOrderVc ()
<
    DriverOrderCellDelegate,
    TopBackViewDelegate,
    UIAlertViewDelegate
>

@property (nonatomic, strong) TopBackView *topBackView;

@end

static NSString * const identifier = @"driverOrderCompetitionCell";

@implementation An_CompetitionOrderVc

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ///1. 添加导航栏
    [self.view addSubview:self.topBackView];

    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
     [self downRefresh];
}

#pragma mark -
#pragma mark - UITableView协议
/**
    Cell个数
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
/**
    Cell风格
 */
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    DriverOrderCell *cell = [DriverOrderCell competitionCellWithTableView:tableView reuseIdentifier:identifier];

    cell.comModel = self.dataArray[indexPath.section];
   
    cell.delegate = self;
    
    return cell;
}
/**
    Cell点击
 */
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self pushOrderdetailVCWithModel:self.dataArray[indexPath.section]];
}
/**
    订单Cell代理
 */
- (void)driverOrderCell:(DriverOrderCell *)cell
             orderState:(DriverOrderState)state{
    switch (state) {
        case DriverOrderStateDeatail:
        {
            [self pushOrderdetailVCWithModel:cell.comModel];
        }
            break;
            //抢单
        case DriverOrderStateCompetition:
        {
            [self cellClickWithComptitionTheOrders:cell.comModel.ID];
        }
            break;
        default:
            break;
    }
}

/**
    推出查看订单详情Vc
 */
- (void)pushOrderdetailVCWithModel:(An_ComptitionOrdersModel *)model {
    
    CompitionOrdersDetailVc *detailVC = [[CompitionOrdersDetailVc alloc] init];
    detailVC.orderModel = model;
    [self.navigationController pushViewController:detailVC animated:YES];
}

/**
    抢单
 */
- (void)cellClickWithComptitionTheOrders:(NSString *)orderID {
 

    __weak typeof(self) weakSelf = self;
    
    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
    [[Common shared] afPostRequestWithUrlString:competeQuickOrderList
                                 parms:@{@"orderId":orderID}
                         finishedBlock:^(id responseObj)
     {
        [WKProgressHUD dismissInView:weakSelf.view animated:YES];
    
         
         NSDictionary *data = [[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil] dictionaryByReplacingNullsWithStrings];

         NSString *str = data[@"message"];
     
         if ([str isEqualToString:@""])
         {
             str = @"抢单失败, message为空!";
         }
         NSString *message = [NSString stringWithFormat:@"\n%@", str];
         
         __weak typeof(self) weakSelf = self;
         
         UIAlertController *alert = [Common sureAlertsControllerWithMessage:message
                                                                     action:^(UIAlertAction *action)
                                     {
                                             if ([data[@"success"] boolValue] != NO)
                                             {
                                                 [weakSelf.navigationController popViewControllerAnimated:YES];
                                             }
                                     }];
         
         [self presentViewController:alert animated:YES completion:nil];
        
         
       
    } failedBlock:^(NSString *errorMsg) {
         [WKProgressHUD dismissInView:weakSelf.view
                             animated:YES];
        
    }];
}


#pragma mark -
#pragma mark - Lazy
- (TopBackView *)topBackView {
    if (!_topBackView)
    {
        _topBackView = [[TopBackView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 64)
                                                    title:@"急发运单"];
        _topBackView.rightButton.hidden = YES;
        _topBackView.delegate = self;
 
    }
    return _topBackView;
}
/**
    导航栏左侧点击
 */
- (void)backViewPopViewController {
     [self.navigationController popViewControllerAnimated:YES];
}

/**
    视图即将加载
 */
- (void)viewWillAppear:(BOOL)animated{
   
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    [rootVC setTabBarHidden:YES];
    
}


#pragma mark -
#pragma mark - 获取服务器数据
/**
 获取所有急发单列表
 ***
 */
- (void)getDataToServerDownRefresh:(BOOL)isDownRefresh {
    
    NSString *urlString = [NSString stringWithFormat:@"%@?pageNo=%lu&pageSize=%@&waybillType=20&orderCode=""&beginDate=""&endDate=""",quickDispatchList,(unsigned long)self.pageNo,@"10"];
    
    __weak typeof(self) weakSelf = self;
    
    NSLog(@"URL=%@", urlString);
    
    [Common requestWithUrlString:urlString contentType:application_json errorShow:YES finished:^(id responseObj) {
        
        [WKProgressHUD dismissInView:weakSelf.view animated:YES];
        
        self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];
        
        if ([responseObj[@"success"] boolValue] != NO)
        {
            
            ///1. 判断
            if (isDownRefresh != YES)
            {
                weakSelf.pageNo ++;
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            else
            {
                if (weakSelf.tableView.mj_footer.hidden != NO)
                {
                    weakSelf.tableView.mj_footer.hidden = NO;
                }
                
                weakSelf.pageNo ++;
                
                [weakSelf.dataArray removeAllObjects];
            }
            
            ///2. 解析
            for (NSDictionary *dic in responseObj[@"data"][@"dWaybillList"])
            {
                
                An_ComptitionOrdersModel *model = [[An_ComptitionOrdersModel alloc]init];
                
                [model setValuesForKeysWithDictionary:[dic dictionaryByReplacingNullsWithStrings]];
                
                [self.dataArray addObject:model];
                
            }
            
            ///3. 再判断
       
            if (self.dataArray.count > 0)
            {
               weakSelf.tableView.backgroundView.hidden = YES;
            }
            else
            {
                weakSelf.tableView.backgroundView.hidden = NO;
                weakSelf.tableBackgroundView.label.text = @"暂无运单";
                weakSelf.tableView.mj_footer.hidden = YES;
            }
            
            ///4. 刷新
            [weakSelf.tableView reloadData];
            
        
        }
        else
        {
            [WKProgressHUD popMessage:responseObj[@"message"]
                               inView:weakSelf.view
                             duration:1.5
                             animated:YES];
        }
        
        
        
    } failed:^(NSString *errorMsg) {
        if (weakSelf.tableView.mj_footer.hidden != NO)
        {
            weakSelf.tableView.mj_footer.hidden = NO;
        }
        [WKProgressHUD dismissInView:weakSelf.view animated:YES];
        NSLog(@"%@",errorMsg);
    }];
    
}


@end
